package cn.itcast.server.service.handler;

import cn.itcast.message.LoginRequestMessage;
import cn.itcast.message.LoginResponseMessage;
import cn.itcast.server.service.UserServiceFactory;
import cn.itcast.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                LoginRequestMessage message) throws Exception {
        String username = message.getUsername();
        String password = message.getPassword();
        boolean result = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage resultMessage;
        if (result) {
            // 将用户与 channel 绑定
            SessionFactory.getSession().bind(ctx.channel(), username);
            resultMessage = new LoginResponseMessage(true, "登陆成功！");
        } else {
            resultMessage = new LoginResponseMessage(false, "登陆失败！");
        }
        // 登录结果写回客户端
        ctx.writeAndFlush(resultMessage);
    }
}
